package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private CheckItemDao checkItemDao;
    @Autowired
    private CheckGroupDao checkGroupDao;


    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;//从属性文件中读取要生成的html对应的目录

    @Autowired
    private JedisPool jedisPool;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    //新增套餐,同时关联检查组
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //新增套餐,操作的是t_setmeal表格
        setmealDao.add(setmeal);
        //设置套餐和检查组多对多的关系,操作的是t_setmeal_checkgroup表格
        Integer setmealId = setmeal.getId();
        setmealAndCheckgroup(setmealId, checkgroupIds);
        //将图片名称保存到数据库中
        String fileName = setmeal.getImg();
        Jedis resource = jedisPool.getResource();
        resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
        resource.close();
        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();

    }

    //生成当前方法所需要的静态页面
    public void generateMobileStaticHtml() {
        //准备模板文件中所需要的数据
        List<Setmeal> setmealList = setmealDao.findAll();
        //生成套餐类表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面(多个)
        generateMobileSetmealDetailHtml(setmealList);

    }

    //生成套餐详情页面
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        Map<String, Object> setmealListmap = new HashMap<>();
        setmealListmap.put("setmealList", setmealList);
        generateHtml("mobile_setmeal.ftl", "m_setmeal.html", setmealListmap);
    }


    //生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> setmealDetialMap = new HashMap<>();
            setmealDetialMap.put("setmeal", setmealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", setmealDetialMap);
        }
    }

    private void generateHtml(String templateName, String htmlPageName, Map<String, Object> map) {
        //获取freemarker的配置对象。
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            template.process(map, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    //查询所以的体检套餐,用于移动端的套餐显示
    public List<Setmeal> getAllSetmeal() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(int id) {
        Setmeal setmeal = setmealDao.findById1(id);
        List<CheckGroup> checkGroupList = checkGroupDao.findCheckGroupById1(setmeal.getId());
        for (CheckGroup checkGroup : checkGroupList) {
            List<CheckItem> checkItemList = checkItemDao.findCheckItemById1(checkGroup.getId());
            checkGroup.setCheckItems(checkItemList);
        }
        setmeal.setCheckGroups(checkGroupList);
        return setmeal;
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        //sql的查询语句的返回值类型为map类型
        return setmealDao.findSetmealCount();
    }

  /*  @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }*/

    private void setmealAndCheckgroup(Integer setmealId, Integer[] checkgroupIds) {
        //首先判断检查组不为空,长度大于0
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            //对检查组的ID数组进行遍历
            for (Integer checkgroupId : checkgroupIds) {
                //将套餐和检查组封装成map集合
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDao.setSetmealAndCheckgroup(map);
            }
        }
    }
}
